<template>
  <!-- <Dialog v-model="dialogVisible" :title="dialogTitle"> -->
    <Form ref="formRef" v-loading="formLoading" :isCol="true" :rules="rules" :schema="allSchemas.formSchema" >
      <template #list="form">
        <UploadFileTo  v-model="form['list']" :updateUrl="updateUrl"  :limit="1" :fileType="['smwu']" :describe="'上传.smwu格式的文件'"  @uploadSuccess="uploadSuccess" @uploadError="uploadError"/>
    </template>
    <template #templateType="form">
        <el-select  v-model="form['templateType']">
          <el-option @click="handSelet(form,item.label)"
            v-for="item in templateTypeOpt"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
    </template>
    <template #imgSize="form">
        <el-select  v-model="form['imgSize']">
          <el-option @click="handImgSize(form,item.label)"
            v-for="item in imgSizeOpt"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
    </template>
    <template #topicType="form">
        <el-select  v-model="form['topicType']">
          <el-option
                v-for="dict in topicTypeOpt"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
        </el-select>
    </template>
    <template #pictureName="form">
        <el-input v-model="form['pictureName']"
          :formatter="(value) => `{地震名称} ${value}`"
          :parser="(value) => value.replace(/\{地震名称}\s?/, '')"
        ></el-input>
    </template>
    <template #sort="form">
        <el-input  v-model="form['sort']"
        :formatter="(value) => `${value}`.replace(/\D/g,'')"
        :parser="(value) => value.replace(/\D/g,'')"
        ></el-input>
    </template>
    <template #createUserName="form">
        <el-input disabled v-model="form['createUserName']"></el-input>
    </template>
    <template #createDeptName="form">
      <el-input disabled v-model="form['createDeptName']"></el-input>
    </template>
    <template #printType="form">
        <el-checkbox v-model="form['printType']">自动打印</el-checkbox>
    </template>
    <template #isShare="form">
        <el-checkbox :disabled="form['templateType']=='公用'" v-model="form['isShare']">共享</el-checkbox>
    </template>
    <template #produceType="form">
        <el-checkbox v-model="form['produceType']">产出</el-checkbox>
    </template>
    </Form>
    <div style="text-align: center;">
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="setClose">取 消</el-button>
    </div>
  <!-- </Dialog> -->
</template>
<script lang="ts" setup>
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import * as imgProduceApi from '@/api/productmange/imgProduce';
import UploadFileTo from '@/views/responseLevel/populationDensity/create/UploadFileReport.vue'

import { imgSizeOpt,templateTypeOpt,userInfo } from '../indexData'

import { allSchemas, rules } from './configuration.data'

defineOptions({ name: 'ConfigurationForm' })
const topicTypeOpt = ref(getDictOptions(DICT_TYPE.TOPICTYPE)) // 专题类型
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formRef = ref() // 表单 Ref

const updateUrl = ref(import.meta.env.VITE_BASE_URL +'/admin-api/attachment/uploadFileSMWU')
/** 打开弹窗 */
const open = async (type: string, id?: number|string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    (await formRef.value.getElFormRef()).resetFields()
    formRef.value.setValues({id:null})
    try {
      const data = await imgProduceApi.getByIdpictureTemplate({id:id})
      // data.imgSize= parseInt(data.imgSize);
      if (data.list.length>0) {
        data.list[0].name = data.list[0].attachName;
        data.list[0].url = data.list[0].attachId;
      }
      data.pictureName = data.pictureName.replace('{地震名称}', '')
      data.printType= data.printType==1?true:false;
      data.isShare= data.isShare==1?true:false;
      data.produceType= data.produceType==1?true:false;
      handImgSize(data,data.imgSize)
      formRef.value.setValues(data)
    } finally {
      formLoading.value = false
    }
  }else{
    (await formRef.value.getElFormRef()).resetFields()
    formRef.value.setValues({id:null})
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
/**
 * 
 * isTest  是否是测试群(0是  1否 )
 * type   类型 (0企业微信  1钉钉)
 * isUse  是否启用(0是  1否)
 */
const emit = defineEmits(['success','setClose','setViewFun']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.getElFormRef().validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formRef.value.formModel;
    data.printType= data.printType==true?1:0;
      data.isShare= data.isShare==true?1:0;
      data.produceType= data.produceType==true?1:0;
      data.createUserId=userInfo.id;
      data.createDeptId=userInfo.deptId;
      data.dataSourceKey=userInfo.divisionCode;
      data.pictureName = '{地震名称}' + data.pictureName;
    if (formType.value === 'create') {
      await imgProduceApi.savepictureTemplate(data)
      message.success(t('common.createSuccess'))
    } else {
      await imgProduceApi.savepictureTemplate(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    emit('setClose')
    setClose()
  } finally {
    formLoading.value = false
  }
}
const setClose=()=>{
  dialogVisible.value = false
  emit('setClose')
}
const handSelet=(form,label)=>{
  form.isShare = label=='公用'?true:false;
}
// 上传成功
const uploadSuccess = (value) => {
  const data={
    templateFileId:value.fileList[0].id,
    templateFileName:value.fileList[0].name,
    templateName:value.fileList[0].name,
    pictureName:value.fileList[0].name,
    list:value.fileList
  }
  formRef.value.setValues(data)
  // formData.value.voList = value;
}
const uploadError=()=>{
  const data={
    templateFileId:'',
    templateFileName:'value.fileList[0].name',
    templateName:'',
    pictureName:'',
    list:[]
  }
  formRef.value.setValues(data)
}
const handImgSize= async (form,label)=>{
  console.log( 'opt',label);
const list= [];
console.log( 'opt',list);
  const opt= await getDictOptions(DICT_TYPE.TOPICTYPE);
  opt.forEach((dict) => {
    console.log( 'dict.label.indexOf(label)',dict.label.indexOf(label));
    if (dict.label.indexOf(label) != -1) {
      list.push(dict)
    }
  })
  console.log( 'list',list);
  
  topicTypeOpt.value=list
}
// topicTypeOpt.value = await 
</script>
